package com.rzjm.api.scheduler;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.api.entity.*;
import com.rzjm.api.service.*;
import com.rzjm.api.util.DateUtil;
import com.rzjm.api.util.OkHttpClientUtil;
import com.rzjm.api.util.WXPayCommonUtil;
import com.rzjm.api.util.WxMessage;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class DataAnalysis {
    private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Value("${web.appidCy}")
    private String appidCy;//图片地址

    @Value("${web.appid_mp}")
    private String appidMp;//图片地址

    @Value("${web.secret_mp}")
    private String secretMp;//图片地址

    @Value("${web.appid_mp_cy}")
    private String appidMpCy;//图片地址

    @Value("${web.secret_mp_cy}")
    private String secretMpCy;//图片地址

    @Value("${web.isLocal}")
    private String isLocal;//图片地址

    @Value("${web.isRsServer}")
    private String isRsServer;//图片地址



    @Resource
    private UserMpService userMpService;
    @Resource
    private TerminalFittingService terminalFittingService;
    @Resource
    private WxTemplateService wxTemplateService;
    @Resource
    private UserService userService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private ShopService shopService;
    @Resource
    private DeviceService deviceService;
    @Resource
    private DeviceRangeService deviceRangeService;
    @Resource
    private FsrDeviceService fsrDeviceService;
    @Resource
    private DeviceWeldingService deviceWeldingService;
    @Resource
    private DeviceWeldingRecordService deviceWeldingRecordService;

    @Value("${web.fsrParentAssetId}")
    private String fsrParentAssetId;

    /**
     *  每 5 分钟执行一次
     *  修改测量设备的在线状态
     */
//    @Scheduled(cron = "0 0/5 * * * ?")
    public void checkRangeDeviceOnlineState() {
        if(isLocal.equals("0")){
            QueryWrapper<DeviceRange> qw = new QueryWrapper<>();
            qw.eq("online_state", 1);
            qw.eq("online_state", 1);
            qw.lt("last_online_time", DateUtil.getAfterSecondsByOld(new Date(), -1200));
            qw.orderByAsc("last_online_time");
            List<DeviceRange> list = deviceRangeService.list(qw);
            if(CollUtil.isNotEmpty(list)){
                for (DeviceRange range : list){
                    Date lastOnlineTime = range.getLastOnlineTime();
                    //当前时间的  20分钟之前的时间   和最后在线时间对比
                    Date checkTime = DateUtil.getAfterSecondsByOld(new Date(), -1200);
                    if(lastOnlineTime.getTime() < checkTime.getTime()){
                        range.setOnlineState(0);
                        range.setLastOfflineTime(new Date());
                        deviceRangeService.resetDevice(range);
                    }
                }
            }
        }
    }


    /**
     *  每 30秒执行一次
     *  获取 断电器设备
     */
    @Scheduled(cron = "0 0/2 * * * ?")
    public void asnycFsrDevice() {
        if(isLocal.equals("0")){
            fsrDeviceService.getDeviceListByAssId(fsrParentAssetId);
        }
    }


    /**
     *  每 1分钟执行一次
     *  获取 断电器设备
     */
//    @Scheduled(cron = "0/10 * * * * ?")
    public void asnycFsrDeviceStatus() {
        if(isLocal.equals("0")){
            fsrDeviceService.getDeviceStatusByApi();
        }
    }


    /**
     *  每 1分钟执行一次
     *  获取 断电器设备在线状态
     */
//    @Scheduled(cron = "0/10 * * * * ?")
    public void asnycFsrDeviceOnlineStatus() {
//        if(isLocal.equals("0")){
            fsrDeviceService.getDeviceOnlineStatusByApi();
//        }
    }

    /**
     *  每 10秒执行一次  超时 自动关闭
     *  获取 断电器设备
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void checkFsrDeviceState() {
        if(isLocal.equals("0")){
            QueryWrapper<DeviceWelding> qw = new QueryWrapper<>();
            Integer[] states = {1 , 2};
            qw.in("use_state",Arrays.asList(states));//使用中的
            List<DeviceWelding> devices = deviceWeldingService.list(qw);
            if(CollUtil.isNotEmpty(devices)){
                for (DeviceWelding device : devices){
                    if(device.getUseState() == 2){
                        if(device.getIsHasBreaker() == 1) {
                            FsrDevice fsrDevice = fsrDeviceService.findById(device.getFsrBreakerId());
                            if (fsrDevice != null) {
                                if(fsrDevice.getIsSelf() == 1){
                                    if(
                                            (device.getUseState() == 2 && new Date().getTime() > device.getUseEndTime().getTime())
                                                    ||
                                                    (device.getUseState() == 0 && fsrDevice.getPowerCodeState() == 1)){


                                        //如果是  超出工作时间了，要执行关闭  并且 自动归还
                                        if(device.getUseState() == 2 && new Date().getTime() > device.getUseEndTime().getTime()){
                                            QueryWrapper<DeviceWeldingRecord> qwFireWork = new QueryWrapper<>();
                                            //非安全区域的  结束后 要 设置成  已归还
                                            if(device.getIsSafe() == 0){
                                                qwFireWork.eq("device_id", device.getId());
                                                qwFireWork.eq("fire_work_id", device.getLastFireWorkId());
                                                qwFireWork.last("limit 1");
                                                DeviceWeldingRecord deviceRecord = deviceWeldingRecordService.getOne(qwFireWork);
                                                if (deviceRecord != null) {
                                                    deviceRecord.setRebackTime(new Date());
                                                    deviceRecord.setState(2);
                                                    deviceWeldingRecordService.updateById(deviceRecord);
                                                }
                                            }else{
                                                //安全区域的
                                                qwFireWork.eq("device_id", device.getId());
                                                qwFireWork.eq("state", 1);
                                                qwFireWork.last("limit 1");
                                                DeviceWeldingRecord deviceRecord = deviceWeldingRecordService.getOne(qwFireWork);
                                                if (deviceRecord != null) {
                                                    deviceRecord.setRebackTime(new Date());
                                                    deviceRecord.setState(2);
                                                    deviceWeldingRecordService.updateById(deviceRecord);
                                                }
                                            }
                                        }

                                        fsrDeviceService.commandOp(fsrDevice, 0);
                                        device.setUseState(0);
//                                    device.setState();
                                        deviceWeldingService.updateById(device);

                                        QueryWrapper<DeviceWeldingRecord> qwRecord = new QueryWrapper<>();
                                        qwRecord.eq("device_id", device.getId());
                                        qwRecord.ne("state", 2);
                                        List<DeviceWeldingRecord> recordList = deviceWeldingRecordService.list(qwRecord);
                                        if (CollUtil.isNotEmpty(recordList)) {
                                            for (DeviceWeldingRecord record : recordList){
                                                record.setRebackTime(new Date());
                                                record.setState(2);//0 - 新申请  1 - 结束  2 - 归还
                                                deviceWeldingRecordService.updateById(record);
                                            }
                                        }
//                                    System.out.println("===========6666666666============");
//                                    System.out.println("企业焊机，执行关闭 未在有效时间内  执行时间： " + DateUtil.getTime()+ "   " + fsrDevice.getId());
                                    }
                                }
                            }
                        }
                    }else if(device.getUseState() == 1){
                        Date useEndTime = device.getUseEndTime();
                        if(useEndTime != null){
                            //当前时间  超过了  结束使用时间  ,如果是还在申请中的话 就 重置 设备状态
                            if(new Date().getTime() > useEndTime.getTime()){
                                device.setUseState(0);
                                deviceWeldingService.updateById(device);

                                FsrDevice fsrDevice = fsrDeviceService.findById(device.getFsrBreakerId());
                                if(fsrDevice != null){
                                    fsrDeviceService.commandOp(fsrDevice, 0);
                                }

                                QueryWrapper<DeviceWeldingRecord> qwRecord = new QueryWrapper<>();
                                qwRecord.eq("device_id", device.getId());
                                qwRecord.ne("state", 2);
                                List<DeviceWeldingRecord> recordList = deviceWeldingRecordService.list(qwRecord);
                                if (CollUtil.isNotEmpty(recordList)) {
                                    for (DeviceWeldingRecord record : recordList){
                                        record.setRebackTime(new Date());
                                        record.setState(2);//0 - 新申请  1 - 结束  2 - 归还
                                        deviceWeldingRecordService.updateById(record);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     *  每 30秒执行一次  超时 自动关闭
     *  获取 断电器设备
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void checkFsrDeviceState1() {
        if(isLocal.equals("0")){
            QueryWrapper<DeviceWelding> qw = new QueryWrapper<>();
            qw.eq("use_state",3);//已经断电的
            List<DeviceWelding> devices = deviceWeldingService.list(qw);
            if(CollUtil.isNotEmpty(devices)){
                for (DeviceWelding device : devices){
                    if(device.getIsHasBreaker() == 1) {
                        FsrDevice fsrDevice = fsrDeviceService.findById(device.getFsrBreakerId());
                        if (fsrDevice != null) {
                            if(fsrDevice.getOnlineState() == 1){
                                fsrDeviceService.commandOp(fsrDevice, 0);

//                                System.out.println("===========55555555555============");
//                                System.out.println("中途断电设备，一旦上线后，自动关闭 ，需重新申请： " + DateUtil.getTime() + "   " + fsrDevice.getId());
                            }
                        }

                        QueryWrapper<DeviceWeldingRecord> qwRecord = new QueryWrapper<>();
                        qwRecord.eq("device_id", device.getId());
                        qwRecord.ne("state", 2);
                        List<DeviceWeldingRecord> recordList = deviceWeldingRecordService.list(qwRecord);
                        if (CollUtil.isNotEmpty(recordList)) {
                            for (DeviceWeldingRecord record : recordList){
                                record.setRebackTime(new Date());
                                record.setState(2);//0 - 新申请  1 - 结束  2 - 归还
                                deviceWeldingRecordService.updateById(record);
                            }
                        }
                        device.setUseState(0);
                        deviceWeldingService.updateById(device);
                    }
                }
            }
        }
    }

    /**
     *  每 5分钟执行一次  14天 为使用的预警
     *  获取 断电器设备
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    public void checkFsrDeviceOnlineState() {
        if(isLocal.equals("0")){
            List<FsrDevice> devices = fsrDeviceService.list();
            if(CollUtil.isNotEmpty(devices)){
                for (FsrDevice device : devices){
                    Date lastOnlineTime = device.getLastOnlineTime();
                    Date lastWarnTime = device.getLastWarnTime();
                    if(lastOnlineTime == null ){
                        lastOnlineTime = new Date();
                        device.setLastOnlineTime(new Date());
                    }
                    Date warnTime = DateUtil.getAfterDayDate(lastOnlineTime, 14);
                    if(lastWarnTime == null){
                        lastWarnTime = new Date();
                        device.setLastWarnTime(lastWarnTime);
                    }

                    Date lastWarnTimeNew = DateUtil.getAfterDayDate(lastWarnTime, 14);
                    if(new Date().getTime() > warnTime.getTime() && new Date().getTime() > lastWarnTimeNew.getTime()){

                        device.setLastWarnTime(new Date());
                        //开始报警
                        fsrDeviceService.updateById(device);

                    }
                }
            }
        }
    }

    /**
     *  每1天  9点  执行一次
     */
    @Scheduled(cron = "0 0 9 * * ?")
    public void getSimCardInfo(){
        try{
            String url = "https://www.znffj.com/ajax/sim/searchsim.ashx?mobile=";
            QueryWrapper<DeviceRange> qw = new QueryWrapper<>();
            qw.isNotNull("sim_card_num");
            List<DeviceRange> devicesList = deviceRangeService.list(qw);
            if(CollUtil.isNotEmpty(devicesList)){
                for (DeviceRange devices : devicesList){
                    if(StrUtil.isNotEmpty(devices.getSimCardNum())){
                        Response response = OkHttpClientUtil.getInstance().getData(url + devices.getSimCardNum());
                        if(response.code() == 200){
                            String body = response.body().string();
                            System.out.println("body: " + body);
                            JSONObject jsonObject = JSONUtil.parseObj(body);
                            if(jsonObject!=null){
                                String active_time = jsonObject.getStr("activation_time");
                                if(StrUtil.isNotEmpty(active_time)){
//                                    devices.setSimExpireTime();
                                    devices.setSimOpenTime(DateUtil.formatDate(active_time));
                                    devices.setSimCardName(jsonObject.getStr("name"));
                                    deviceRangeService.updateById(devices);
                                }
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //每天上午9点发送距离还剩7天内的保养设备名单
//    @Scheduled(cron = "0 0 9 * * ?")
    public void testTasks() {
        if(isLocal.equals("0")){
            List<Map<String,Object>> fittings = terminalFittingService.getWarningPageByUserId(7);
            if(fittings != null){
                fittings.forEach(fitting->{
                    sendWxMsg(fitting);//发送推送消息
                });
            }
        }
    }

    /**
     *  每15分钟检测一次
     */
    @Scheduled(cron = "0 0/13 * * * ?")
    public void deviceOnline() {
        if(isRsServer.equals("1")) {
            QueryWrapper<Device> qw = new QueryWrapper<>();
            qw.eq("device_type", 2);
            List<Device> list = deviceService.list(qw);

            String accessToken = wxTemplateService.getAccessToken(appidMp,secretMp, 1);

            for (Device device : list) {
                Date lastActiveTime = device.getLastActiveTime();
                Date checkTime = DateUtil.getAfterSecondsByOld(lastActiveTime, 15 * 60);
                System.out.println("最后一次在线时间：" + DateUtil.getTime(checkTime));


                Date checkOnlineTime = DateUtil.getAfterSecondsByOld(lastActiveTime, 2 * 60);

                if (new Date().getTime() > checkOnlineTime.getTime()) {
                    device.setOnlineState(0);
                    deviceService.updateById(device);
                }


                //最后一次的交互时间已经超过了15分钟
                if (new Date().getTime() > checkTime.getTime()) {
                    System.out.println("已超15分钟 ：" + DateUtil.getTime(checkTime));
//                    wxTemplateService.sendWxMsgOffline(device,accessToken );
                }
            }
        }
    }

    private void sendWxMsg(Map<String,Object> map){
        try{
            String accessToken = wxTemplateService.getAccessToken(appidMp,secretMp, 1);
            Shop shop = shopService.selectById((int)map.get("shop_id"));
            QueryWrapper<SysUser> qw = new QueryWrapper<>();
            qw.eq("shop_id",map.get("shop_id"))
                    .and(wrapper -> wrapper.eq("user_type", 4).or().eq("user_type", 6));
            List<SysUser> sysUsers = sysUserService.list(qw);
            if(sysUsers != null && sysUsers.size() > 0){
                for(SysUser sysUser : sysUsers){
                    List<User> users = userService.selectListByColumn("sys_user_id",sysUser.getUserId());
                    if(users != null){
                        for (User user :users){
                            if(user != null && sysUser.getIsSendMsg() == 1 && StrUtil.isNotEmpty(user.getUnionId())){
                                WxMsgTemplate template = getTemplate(map,shop,user);
//                                System.out.println("模板消息：" + template.toString());
                                String param = JSONUtil.parseObj(template).toString();
                                WxMessage.sendMsg(accessToken,param);
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("发送失败" + e.getMessage());
        }
    }

    private WxMsgTemplate getTemplate(Map<String,Object> map,Shop shop,User user){

        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",2);
        UserMp userMp = userMpService.selectByUniqueColumn("unionid",user.getUnionId());
        if(userMp!=null){
            template.setTouser(userMp.getOpenid());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");

            Map<String,Object> miniprogram = new HashMap<>();
            miniprogram.put("appid",appidCy);
            miniprogram.put("pagepath","/pages/terminal/healthlist/index?state=0");
            template.setMiniprogram(miniprogram);

            Map<String, MsgTempData> m = new HashMap<String, MsgTempData>();

            MsgTempData first = new MsgTempData();
            first.setColor(wxTemplate.getFontColor());
            first.setValue("管理员您好，有设备需要进行保养");
            m.put("first",first);

            //计划名称
            MsgTempData keyword1 = new MsgTempData();
            keyword1.setColor(wxTemplate.getFontColor());
            keyword1.setValue(shop.getShopName() + "设备保养");
            m.put("keyword1",keyword1);

            //到期时间
            MsgTempData keyword2 = new MsgTempData();
            keyword2.setColor(wxTemplate.getSpicalFontColor());
            keyword2.setValue("还剩余大约7天时间");
            m.put("keyword2",keyword2);

            //相关设备
            MsgTempData keyword3 = new MsgTempData();
            keyword3.setColor(wxTemplate.getFontColor());
            keyword3.setValue("共" + map.get("terminal_count") + "台待保养");
            m.put("keyword3",keyword3);

            MsgTempData remark = new MsgTempData();
            remark.setColor(wxTemplate.getFontColor());
            remark.setValue("请尽快对设备进行保养。");
            m.put("remark",remark);

            template.setData(m);
        }
        return template;
    }

    //每天上午9点发送距离还剩7天内的保养设备名单
//    @Scheduled(cron = "0 0 9 * * ?")
    public void warnSurvey() {
        if(isLocal.equals("0")) {
            List<Map<String, Object>> fittings = terminalFittingService.getWarningPageByUserId(7);
            if (fittings != null) {
                fittings.forEach(fitting -> {
                    sendWxMsg(fitting);//发送推送消息
                });
            }
        }
    }

    //每5分钟执行一次
    @Scheduled(cron = "0 0 0/1 * * ?")
    public void userMp() {
        if(isLocal.equals("0")){
            System.out.println("定时任务执行时间：" + simpleDateFormat.format(new Date()));
//            String accessToken = WxMessage.getACCESSTOKEN(appidMp,secretMp);
            String accessToken = wxTemplateService.getAccessToken(appidMp,secretMp,1);
            System.out.println("accessToken:" + accessToken);
            JSONObject jsonObject = WxMessage.getUserMp(accessToken,"");
            if(jsonObject != null){
                System.out.println("卓宇云 同步公众号用户： " + jsonObject.toString());
                if(!jsonObject.containsKey("errcode") && jsonObject.getJSONObject("data").containsKey("openid")){
                    JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("openid");
                    if(jsonArray != null && jsonArray.size() > 0) {
                        for (int i = 0; i < jsonArray.size(); i++) {
                            String openid = jsonArray.getStr(i);
                            JSONObject userInfo = WxMessage.getUserMpInfo(accessToken,openid);
                            if(userInfo!=null && userInfo.size() > 0){
                                String openId = userInfo.getStr("openid");
                                String unionId = userInfo.getStr("unionid");
                                String nickname = userInfo.getStr("nickname");
                                String faceurl = userInfo.getStr("headimgurl");

                                QueryWrapper<UserMp> qw = new QueryWrapper<>();
                                qw.eq("unionid",unionId);
                                qw.eq("mp_type","zhuoyu");
                                qw.last("limit 1");
                                UserMp userMp = userMpService.getOne(qw);
                                if(userMp == null){
                                    userMp = new UserMp();
                                    userMp.setMpType("zhuoyu");
                                    userMp.setOpenid(openId);
                                    userMp.setUnionid(unionId);
                                    userMp.setFaceUrl(faceurl);
                                    userMp.setNickName(nickname);
                                    userMp.setCreateTime(new Date());
                                    if(StrUtil.isNotEmpty(openId)){
                                        boolean bl = userMpService.save(userMp);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    //每5分钟执行一次
    @Scheduled(cron = "0 0/25 * * * ?")
    public void userMpCy() {
        if(isLocal.equals("0")){
            System.out.println("琤一数字公众号 定时任务执行时间：" + simpleDateFormat.format(new Date()));
            String accessToken = wxTemplateService.getAccessToken(appidMpCy,secretMpCy,1);
            System.out.println("accessToken:" + accessToken);
            JSONObject jsonObject = WxMessage.getUserMp(accessToken,"");
            if(jsonObject != null){
                System.out.println("同步公众号用户： " + jsonObject.toString());
                if(!jsonObject.containsKey("errcode") && jsonObject.getJSONObject("data").containsKey("openid")){
                    JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("openid");
                    if(jsonArray != null && jsonArray.size() > 0) {
                        for (int i = 0; i < jsonArray.size(); i++) {
                            String openid = jsonArray.getStr(i);
                            JSONObject userInfo = WxMessage.getUserMpInfo(accessToken,openid);
                            if(userInfo!=null && userInfo.size() > 0){
                                String openId = userInfo.getStr("openid");
                                String unionId = userInfo.getStr("unionid");
                                String nickname = userInfo.getStr("nickname");
                                String faceurl = userInfo.getStr("headimgurl");
                                QueryWrapper<UserMp> qw = new QueryWrapper<>();
                                qw.eq("unionid",unionId);
                                qw.eq("mp_type","cy");
                                qw.last("limit 1");
                                UserMp userMp = userMpService.getOne(qw);
                                if(userMp == null){
                                    userMp = new UserMp();
                                    userMp.setMpType("cy");
                                    userMp.setOpenid(openId);
                                    userMp.setUnionid(unionId);
                                    userMp.setFaceUrl(faceurl);
                                    userMp.setNickName(nickname);
                                    userMp.setCreateTime(new Date());
                                    if(StrUtil.isNotEmpty(openId)){
                                        boolean bl = userMpService.save(userMp);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    //每1分钟执行一次
//    @Scheduled(cron = "0 0/1 * * * ?")
    private void deviceFireState(){
        System.out.println("deviceFireState 定时任务执行时间：" + simpleDateFormat.format(new Date()));
        List<Device> list = deviceService.selectListByColumn("device_type",1);
        if(list!=null && list.size() > 0){
            for (Device device : list){
                String url = "https://chargesocket.tlrobo.cn/ajax/showhow/getsocketstatus.ashx?sn="+  device.getDeviceNum();
                System.out.println("url:" + url);
                String result = WXPayCommonUtil.httpsRequest(url, "GET","");
                System.out.println("请求电焊机的操作返回结果：" + result);
                //{"code":1,"res":true,"msg":"请求成功","data":{"online":true,"sn":"12000002"}}
                if(StrUtil.isNotEmpty(result)){
                    JSONObject jsonObject = JSONUtil.parseObj(result);
                    if(jsonObject!=null){
                        boolean bl = jsonObject.getBool("res");
                        if(bl){
                            String data = jsonObject.getStr("data");
                            JSONObject jsonObjectData = JSONUtil.parseObj(data);
                            if(jsonObjectData!=null){
                                boolean online = jsonObjectData.getBool("online");
                                if(online){
                                    device.setOnlineState(1);
                                }else{
                                    device.setOnlineState(0);
                                }
                                deviceService.updateById(device);
                            }
                        }
                    }
                }
            }
        }
    }



    /**
     *  每天晚上22点开始执行数据同步
     *  获取
     */
    @Scheduled(cron = "0 5 22 * * ?")
    public void snycProvData() {
        if(isLocal.equals("0")){
            shopService.uploadData(0);
        }
    }

}
